package com.cloudeye.logtest.basic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * Created by lafangyuan on 2021/1/28.
 */
@Slf4j
public class ThreadPoolCase {

    int corePoolSize = 1;
    /**
     * 注意：maximumPoolSize>=corePoolSize
     */
    int maximumPoolSize = 1;
    long keepAliveTime = 0;
    BlockingQueue workQueue = new ArrayBlockingQueue(1);
    /**
     * 先放到corePool里面，放满了然后就放到workQueue里面，发现也满了，然后创建新线程，从队列中取。
     * 也就是说，如果workQueue里面没有满，那么是不会去扩展线程的。
     * 主要workQueue满了，就会去创建线程，创建不了就拒绝：RejectedExecutionHandler。
     */
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, workQueue,
            new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    log.info("线程放不下了:{}" , executor.getActiveCount());
                }
            });
    public static void main(String[] args) {
        new ThreadPoolCase().run();
    }
    public void run(){

        for(int i=0;i<3;i++){
            threadPoolExecutor.submit(
               new Worker()
            );
        }
    }

    static class Worker implements Runnable{

        @Override
        public void run() {
            try {
                log.info("执行任务：{}",Thread.currentThread().getId());
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
